package com.fau.om.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fau.om.entity.MedicalAdmin;
import com.fau.om.entity.MedicalCallCustomer;
import com.fau.om.entity.MedicalCallTelInfo;
import com.fau.om.entity.MedicalFinancialOrders;
import com.fau.om.entity.MedicalKeyValue;
import com.fau.om.entity.MedicalLogistics;
import com.fau.om.entity.MedicalOrderReconciliation;
import com.fau.om.entity.MedicalOrdersCancel;
import com.fau.om.entity.MedicalOrdersPass;
import com.fau.om.entity.MedicalOrdersProduct;
import com.fau.om.entity.MedicalOrdersStorage;
import com.fau.om.entity.MedicalOrdersWaitDelivery;
import com.fau.om.service.IMaintainManagerService;
import com.fau.om.util.Page;
import com.fau.om.util.ParamUtil;
import com.fau.om.util.SystemConfig;

@Service
@Transactional(readOnly = true)
public class MaintainManagerService extends BaseService implements
		IMaintainManagerService {

	@Override
	public Page findPassByPage(MedicalOrdersPass ordersPass,
			Map<String, Object> map) {
		 
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrdersPass a where 1=1 and a.hospitalId=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalOrdersPass a where 1=1 and a.hospitalId=?");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(ordersPass.getHospitalId());
		
		if(StringUtils.isNotBlank(ordersPass.getSerialNum())) {
			countSql.append(" and a.serialNum = ? ");
			statusSql.append(" and a.serialNum = ? ");
			objectList.add(ordersPass.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(ordersPass.getExpressId())) {
			countSql.append(" and a.expressId = ? ");
			statusSql.append(" and a.expressId = ? ");
			objectList.add(ordersPass.getExpressId());
		}
		
		if(StringUtils.isNotBlank(ordersPass.getName())) {
			countSql.append(" and a.name = ? ");
			statusSql.append(" and a.name = ? ");
			objectList.add(ordersPass.getName());
		}
		
		if(null != ordersPass.getCreateTime()) {
			countSql.append(" and a.createTime > ? ");
			statusSql.append(" and a.createTime > ? ");
			objectList.add(ordersPass.getCreateTime());
		}
		
		if(null != ordersPass.getStartTime()) {
			countSql.append(" and a.checkTime >= ? ");
			statusSql.append(" and a.checkTime >= ? ");
			objectList.add(ordersPass.getStartTime());
		}
		
		if(null != ordersPass.getEndTime()) {
			countSql.append(" and a.checkTime <= ? ");
			statusSql.append(" and a.checkTime <= ? ");
			objectList.add(ordersPass.getEndTime());
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils .isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])){
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]); 
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		
		List<MedicalOrdersPass> list = new ArrayList<MedicalOrdersPass>();
		for(Object obj : page.getResult()) {
			MedicalOrdersPass bean = (MedicalOrdersPass) obj;
			MedicalAdmin cusSer = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, bean.getCusSerId());
			MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, bean.getCheckUserId());
			bean.setCusSerName(cusSer.getName());
			bean.setCheckUserName(checkUser.getName());
			list.add(bean);
		}
		page.setResult(list);
		
		return page;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalOrdersProduct> findProductByOid(String oid) {
		return this.iBaseDao.getBySql("from MedicalOrdersProduct a where a.ordersId=? ", null, oid);
	}

	@Override
	public MedicalOrdersStorage findOrdersStorageById(String id) {
		MedicalOrdersStorage orders = (MedicalOrdersStorage) this.iBaseDao.getObject(MedicalOrdersStorage.class, id);
		MedicalCallCustomer customer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, orders.getCustomerId());
		orders.setMoney(customer.getMoney());
		orders.setRedEnvelopes(customer.getRedEnvelopes());
		orders.setIntegral(customer.getIntegral());
		return orders;
	}

	@Override
	public MedicalCallCustomer findCustomerById(String id) {
		return (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, id);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean cancelOrders(MedicalOrdersPass ordersPass) {
		MedicalOrdersStorage ordersStorage = (MedicalOrdersStorage) this.iBaseDao.getObject(MedicalOrdersStorage.class, ordersPass.getId());
		if(SystemConfig.ORDERS_DELIVERY_TYPE.equals(ordersStorage.getWarehouseStatus())) {
			return false;
		} else {
			MedicalOrdersPass bean = (MedicalOrdersPass) this.iBaseDao.getObject(MedicalOrdersPass.class, ordersPass.getId());
			MedicalOrdersCancel ordersCancel = new MedicalOrdersCancel();
			BeanUtils.copyProperties(bean, ordersCancel);
			ordersCancel.setReasonType(ordersPass.getReasonType());
			ordersCancel.setReasonRemark(ordersPass.getReasonRemark());
			this.iBaseDao.addObject(ordersCancel);
			
			MedicalOrdersWaitDelivery ordersWaitDelivery = (MedicalOrdersWaitDelivery) this.iBaseDao.getObject(MedicalOrdersWaitDelivery.class, ordersPass.getId());
			if(null != ordersWaitDelivery) {
				this.iBaseDao.deleteObject(ordersWaitDelivery);
			}
			MedicalFinancialOrders financialOrders = (MedicalFinancialOrders) this.iBaseDao.getObject(MedicalFinancialOrders.class, ordersPass.getId());
			if(null != financialOrders) {
				this.iBaseDao.deleteObject(financialOrders);
			}
			MedicalOrderReconciliation orderReconciliation = (MedicalOrderReconciliation) this.iBaseDao.getObject(MedicalOrderReconciliation.class, ordersPass.getId());
			if(null != orderReconciliation) {
				this.iBaseDao.deleteObject(orderReconciliation);
			}
			ordersStorage.setOrdersStatus(SystemConfig.ORDERS_AUDIT_CANCEL_TYPE);
			ordersStorage.setWarehouseStatus("");	// 货到付款订单取消了，更改仓储订单状态为无
			ordersStorage.setFinancialStatus("");	// 线下汇款订单取消了，更改财务状态为无。
			ordersStorage.setReasonType(ordersPass.getReasonType());
			ordersStorage.setReasonRemark(ordersPass.getReasonRemark());
			this.iBaseDao.deleteObject(bean);
			
			MedicalCallCustomer customer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, ordersStorage.getCustomerId());
			customer.setMoney(customer.getMoney().add(ordersStorage.getUseMoney()));			// 加回余额
			customer.setIntegral(customer.getIntegral() + ordersStorage.getUsePoints());		// 积分
			customer.setRedEnvelopes(customer.getRedEnvelopes() + ordersStorage.getUseRed() - ordersStorage.getRed());	// 红包
			
			return true;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Page findStorageByPage(MedicalOrdersStorage ordersStorage,
			Map<String, Object> map) {
		
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrdersStorage a where 1=1 and a.hospitalId=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalOrdersStorage a where 1=1 and a.hospitalId=?");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(ordersStorage.getHospitalId());
		
		if(StringUtils.isNotBlank(ordersStorage.getSerialNum())) {
			countSql.append(" and a.serialNum = ? ");
			statusSql.append(" and a.serialNum = ? ");
			objectList.add(ordersStorage.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(ordersStorage.getExpressId())) {
			countSql.append(" and a.expressId = ? ");
			statusSql.append(" and a.expressId = ? ");
			objectList.add(ordersStorage.getExpressId());
		}
		
		if(StringUtils.isNotBlank(ordersStorage.getName())) {
			countSql.append(" and a.name like ? ");
			statusSql.append(" and a.name like ? ");
			objectList.add("%"+ordersStorage.getName()+"%");
		}
		
		if(null != ordersStorage.getCreateTime()) {
			countSql.append(" and a.createTime > ? ");
			statusSql.append(" and a.createTime > ? ");
			objectList.add(ordersStorage.getCreateTime());
		}
		
		if(null != ordersStorage.getStartTime()) {
			countSql.append(" and a.checkTime >= ? ");
			statusSql.append(" and a.checkTime >= ? ");
			objectList.add(ordersStorage.getStartTime());
		}
		
		if(null != ordersStorage.getEndTime()) {
			countSql.append(" and a.checkTime <= ? ");
			statusSql.append(" and a.checkTime <= ? ");
			objectList.add(ordersStorage.getEndTime());
		}
		
		if(null != ordersStorage.getStartTime2()) {
			countSql.append(" and a.createTime >= ? ");
			statusSql.append(" and a.createTime >= ? ");
			objectList.add(ordersStorage.getStartTime2());
		}
		
		if(null != ordersStorage.getEndTime2()) {
			countSql.append(" and a.createTime <= ? ");
			statusSql.append(" and a.createTime <= ? ");
			objectList.add(ordersStorage.getEndTime2());
		}
		
		if(StringUtils.isNotBlank(ordersStorage.getCheckUserId())){
			countSql.append(" and a.checkUserId = ? ");
			statusSql.append(" and a.checkUserId = ? ");
			objectList.add(ordersStorage.getCheckUserId());
		}
		
		if(StringUtils.isNotBlank(ordersStorage.getKeyType()) && StringUtils.isNotBlank(ordersStorage.getStatus()) ) {
			if(ordersStorage.getKeyType().equals(SystemConfig.CM_SYSTEM_TYPE)) {
				countSql.append(" and a.callStatus = ?");
				statusSql.append(" and a.callStatus = ?");
				objectList.add(ordersStorage.getStatus());
			}
			
			if(ordersStorage.getKeyType().equals(SystemConfig.OM_SYSTEM_TYPE)) {
				countSql.append(" and a.ordersStatus = ?");
				statusSql.append(" and a.ordersStatus = ?");
				objectList.add(ordersStorage.getStatus());
			}
			
			if(ordersStorage.getKeyType().equals(SystemConfig.WM_SYSTEM_TYPE)) {
				countSql.append(" and a.warehouseStatus = ?");
				statusSql.append(" and a.warehouseStatus = ?");
				objectList.add(ordersStorage.getStatus());
			}
			
			if(ordersStorage.getKeyType().equals(SystemConfig.FM_SYSTEM_TYPE)) {
				countSql.append(" and a.financialStatus = ?");
				statusSql.append(" and a.financialStatus = ?");
				objectList.add(ordersStorage.getStatus());
			}
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils .isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])){
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]); 
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		
		List<MedicalOrdersStorage> list = new ArrayList<MedicalOrdersStorage>();
		for(Object obj : page.getResult()) {
			ordersStorage = (MedicalOrdersStorage) obj;
			// 订单详细
			List<MedicalOrdersProduct> ordersProductList = this.iBaseDao.getBySql("from MedicalOrdersProduct a where a.ordersId=? ", null, ordersStorage.getId());
			
			ordersStorage.setTotalMoney(ordersStorage.getPayment().add(ordersStorage.getFreight()));
			StringBuilder ordersDetail = new StringBuilder("");
			for(MedicalOrdersProduct ordersProduct : ordersProductList) {
				ordersDetail.append(ordersProduct.getMedicine().getName());
				ordersDetail.append("*");
				ordersDetail.append(ordersProduct.getQuantity());
				ordersDetail.append("; ");
			}
			if(StringUtils.isNotBlank(ordersDetail.toString())) {
				ordersDetail.deleteCharAt(ordersDetail.lastIndexOf("; "));
			}
			ordersStorage.setOrdersDetail(ordersDetail.toString());
			
			MedicalLogistics logistics = (MedicalLogistics) this.iBaseDao.getObject(MedicalLogistics.class, ordersStorage.getExpressId());
			if(null != logistics) {
				ordersStorage.setExpressName(logistics.getName());
			}
			
			MedicalAdmin admin = (MedicalAdmin) this.iBaseDao.getObjectByHql("from MedicalAdmin a where a.id=? and a.enterpriseId=? ",ordersStorage.getCheckUserId() , ordersStorage.getHospitalId());
			if( null != admin){
				ordersStorage.setCheckUserName(admin.getName());
			}
			list.add(ordersStorage);
		}
		page.setResult(list);
		
		return page;
	}

	@Override
	public Workbook exportOrdersCurrent(String ids) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CANCEL);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] ordersIds =  ids.split(",");
			for(int j=0;j<ordersIds.length;j++){
				// 获得记录
				MedicalOrdersPass order = (MedicalOrdersPass) this.iBaseDao.getObject(MedicalOrdersPass.class, ordersIds[j]);
				i++;
				Row currentRow = sheet.createRow(i);
				currentRow.createCell(0).setCellValue(i);
				if(null != order){
					currentRow.createCell(1).setCellValue(order.getSerialNum());
					MedicalAdmin cusSer = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, order.getCusSerId());
					currentRow.createCell(2).setCellValue(cusSer.getName());
					currentRow.createCell(3).setCellValue(DateFormatUtils.format(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
					currentRow.createCell(4).setCellValue(order.getName());
					currentRow.createCell(5).setCellValue(order.getProvince().getpName());
					currentRow.createCell(6).setCellValue(order.getCity().getcName());
					currentRow.createCell(7).setCellValue(order.getDistrict().getdName());
					currentRow.createCell(8).setCellValue(order.getAddress());
					BigDecimal total = new BigDecimal(0);
					if(null != order.getPayment()) {
						total = total.add(order.getPayment());
					}
					if(null != order.getFreight()) {
						currentRow.createCell(12).setCellValue(order.getFreight().toString());
						total = total.add(order.getFreight());
					}
					currentRow.createCell(9).setCellValue(total.toString());
					MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, order.getCheckUserId());
					if(null != checkUser) {
						currentRow.createCell(10).setCellValue(checkUser.getName());
					}
					currentRow.createCell(11).setCellValue(DateFormatUtils.format(order.getCheckTime(), "yyyy-MM-dd HH:mm:ss"));
				}
			}
		}
		return workbook;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportOrdersAll(MedicalOrdersPass ordersPass)throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CANCEL);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		StringBuilder hql = new StringBuilder("from MedicalOrdersPass a where 1=1 and a.hospitalId=? order by a.createTime ");
		List<MedicalOrdersPass> ordersList = this.iBaseDao.getBySql(hql.toString(), null, ordersPass.getHospitalId());
		
		// 遍历
		for (MedicalOrdersPass order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				MedicalAdmin cusSer = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, order.getCusSerId());
				currentRow.createCell(2).setCellValue(cusSer.getName());
				currentRow.createCell(3).setCellValue(DateFormatUtils.format(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
				currentRow.createCell(4).setCellValue(order.getName());
				currentRow.createCell(5).setCellValue(order.getProvince().getpName());
				currentRow.createCell(6).setCellValue(order.getCity().getcName());
				currentRow.createCell(7).setCellValue(order.getDistrict().getdName());
				currentRow.createCell(8).setCellValue(order.getAddress());
				BigDecimal total = new BigDecimal(0);
				if(null != order.getPayment()) {
					total = total.add(order.getPayment());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(12).setCellValue(order.getFreight().toString());
					total = total.add(order.getFreight());
				}
				currentRow.createCell(9).setCellValue(total.toString());
				MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, order.getCheckUserId());
				if(null != checkUser) {
					currentRow.createCell(10).setCellValue(checkUser.getName());
				}
				currentRow.createCell(11).setCellValue(DateFormatUtils.format(order.getCheckTime(), "yyyy-MM-dd HH:mm:ss"));
			}
		}
		return workbook;
	}

	@Override
	public Workbook exportSearchOrdersCurrent(String ids) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_FIND);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		if(StringUtils.isNotBlank(ids)){
			String [] ordersIds =  ids.split(",");
			for(int j=0;j<ordersIds.length;j++){
				// 获得记录
				MedicalOrdersStorage order = (MedicalOrdersStorage) this.iBaseDao.getObject(MedicalOrdersStorage.class, ordersIds[j]);
				Row currentRow = sheet.createRow(j + 2);
				currentRow.createCell(0).setCellValue(j + 1);
				if(null != order){
					currentRow.createCell(1).setCellValue(order.getSerialNum());
					currentRow.createCell(2).setCellValue(DateFormatUtils.format(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
					currentRow.createCell(3).setCellValue(order.getName());
					
					String callStatus = order.getCallStatus();
					if(SystemConfig.ORDERS_IMPORT_TYPE.equals(callStatus)) {
						callStatus = "正在输入";
					} else if(SystemConfig.ORDERS_UNDER_TYPE.equals(callStatus)) {
						callStatus = "已下单";
					}
					currentRow.createCell(4).setCellValue(callStatus);
					
					String ordersStatus = order.getOrdersStatus();
					if(SystemConfig.ORDERS_WAIT_AUDIT_TYPE.equals(ordersStatus)) {
						ordersStatus = "待审核";
					} else if(SystemConfig.ORDERS_AUDIT_PASS_TYPE.equals(ordersStatus)) {
						ordersStatus = "审核通过";
					} else if(SystemConfig.ORDERS_AUDIT_NOPASS_TYPE.equals(ordersStatus)) {
						ordersStatus = "审核未通过";
					} else if(SystemConfig.ORDERS_AUDIT_INVALID_TYPE.equals(ordersStatus)) {
						ordersStatus = "无效订单";
					} else if(SystemConfig.ORDERS_AUDIT_CANCEL_TYPE.equals(ordersStatus)) {
						ordersStatus = "取消订单";
					}
					currentRow.createCell(5).setCellValue(ordersStatus);
					
					String warehouseStatus = order.getWarehouseStatus();
					if(SystemConfig.ORDERS_WAIT_DELIVERY_TYPE.equals(warehouseStatus)) {
						warehouseStatus =  "待发货";
					} else if(SystemConfig.ORDERS_DELIVERY_TYPE.equals(warehouseStatus)) {
						warehouseStatus =  "已发货";
					} else if(SystemConfig.ORDERS_RETREAT_TYPE.equals(warehouseStatus)) {
						warehouseStatus =  "退单";
					} else if(SystemConfig.ORDERS_SIGN_TYPE.equals(warehouseStatus)) {
						warehouseStatus =  "签收";
					}
					currentRow.createCell(6).setCellValue(warehouseStatus);
					
					String financialStatus = order.getFinancialStatus();
					if(SystemConfig.BE_RECONCILED.equals(financialStatus)) {
						financialStatus = "待对账";
					} else if(SystemConfig.HAS_RECONCILED.equals(financialStatus)) {
						financialStatus = "已对账";
					} else if(SystemConfig.HAS_SECTIONED.equals(financialStatus)) {
						financialStatus = "已回款";
					}
					currentRow.createCell(7).setCellValue(financialStatus);
					currentRow.createCell(8).setCellValue(order.getContactNo());
					BigDecimal total = new BigDecimal(0);
					if(null != order.getPayment()) {
						total = total.add(order.getPayment());
					}
					if(null != order.getFreight()) {
						total = total.add(order.getFreight());
					}
					currentRow.createCell(9).setCellValue(total.toString());
					currentRow.createCell(10).setCellValue(order.getProvince().getpName());
					currentRow.createCell(11).setCellValue(order.getCity().getcName());
					currentRow.createCell(12).setCellValue(order.getDistrict().getdName());
					currentRow.createCell(13).setCellValue(order.getAddress());
					
					MedicalLogistics logistics = (MedicalLogistics) this.iBaseDao.getObject(MedicalLogistics.class, order.getExpressId());
					if(null != logistics) {
						currentRow.createCell(14).setCellValue(logistics.getName());
					}
					currentRow.createCell(15).setCellValue(order.getExpressNo());
					if(null != order.getDeliveryTime()) {
						currentRow.createCell(16).setCellValue(DateFormatUtils.format(order.getDeliveryTime(), "yyyy-MM-dd HH:mm:ss"));
					}
				}
			}
		}
		return workbook;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportSearchOrdersAll(MedicalOrdersStorage ordersStorage)
			throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_FIND);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=1;
		StringBuilder hql = new StringBuilder("from MedicalOrdersStorage a where 1=1 and a.hospitalId=? order by a.createTime ");
		List<MedicalOrdersStorage> ordersList = this.iBaseDao.getBySql(hql.toString(), null, ordersStorage.getHospitalId());
		
		// 遍历
		for (MedicalOrdersStorage order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(DateFormatUtils.format(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
				currentRow.createCell(3).setCellValue(order.getName());
				
				String callStatus = order.getCallStatus();
				if(SystemConfig.ORDERS_IMPORT_TYPE.equals(callStatus)) {
					callStatus = "正在输入";
				} else if(SystemConfig.ORDERS_UNDER_TYPE.equals(callStatus)) {
					callStatus = "已下单";
				}
				currentRow.createCell(4).setCellValue(callStatus);
				
				String ordersStatus = order.getOrdersStatus();
				if(SystemConfig.ORDERS_WAIT_AUDIT_TYPE.equals(ordersStatus)) {
					ordersStatus = "待审核";
				} else if(SystemConfig.ORDERS_AUDIT_PASS_TYPE.equals(ordersStatus)) {
					ordersStatus = "审核通过";
				} else if(SystemConfig.ORDERS_AUDIT_NOPASS_TYPE.equals(ordersStatus)) {
					ordersStatus = "审核未通过";
				} else if(SystemConfig.ORDERS_AUDIT_INVALID_TYPE.equals(ordersStatus)) {
					ordersStatus = "无效订单";
				} else if(SystemConfig.ORDERS_AUDIT_CANCEL_TYPE.equals(ordersStatus)) {
					ordersStatus = "取消订单";
				}
				currentRow.createCell(5).setCellValue(ordersStatus);
				
				String warehouseStatus = order.getWarehouseStatus();
				if(SystemConfig.ORDERS_WAIT_DELIVERY_TYPE.equals(warehouseStatus)) {
					warehouseStatus =  "待发货";
				} else if(SystemConfig.ORDERS_DELIVERY_TYPE.equals(warehouseStatus)) {
					warehouseStatus =  "已发货";
				} else if(SystemConfig.ORDERS_RETREAT_TYPE.equals(warehouseStatus)) {
					warehouseStatus =  "退单";
				} else if(SystemConfig.ORDERS_SIGN_TYPE.equals(warehouseStatus)) {
					warehouseStatus =  "签收";
				}
				currentRow.createCell(6).setCellValue(warehouseStatus);
				
				String financialStatus = order.getFinancialStatus();
				if(SystemConfig.BE_RECONCILED.equals(financialStatus)) {
					financialStatus = "待对账";
				} else if(SystemConfig.HAS_RECONCILED.equals(financialStatus)) {
					financialStatus = "已对账";
				} else if(SystemConfig.HAS_SECTIONED.equals(financialStatus)) {
					financialStatus = "已回款";
				}
				currentRow.createCell(7).setCellValue(financialStatus);
				currentRow.createCell(8).setCellValue(order.getContactNo());
				BigDecimal total = new BigDecimal(0);
				if(null != order.getPayment()) {
					total = total.add(order.getPayment());
				}
				if(null != order.getFreight()) {
					total = total.add(order.getFreight());
				}
				currentRow.createCell(9).setCellValue(total.toString());
				currentRow.createCell(10).setCellValue(order.getProvince().getpName());
				currentRow.createCell(11).setCellValue(order.getCity().getcName());
				currentRow.createCell(12).setCellValue(order.getDistrict().getdName());
				currentRow.createCell(13).setCellValue(order.getAddress());
				
				MedicalLogistics logistics = (MedicalLogistics) this.iBaseDao.getObject(MedicalLogistics.class, order.getExpressId());
				if(null != logistics) {
					currentRow.createCell(14).setCellValue(logistics.getName());
				}
				currentRow.createCell(15).setCellValue(order.getExpressNo());
				if(null != order.getDeliveryTime()) {
					currentRow.createCell(16).setCellValue(DateFormatUtils.format(order.getDeliveryTime(), "yyyy-MM-dd HH:mm:ss"));
				}
			}
		}
		return workbook;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalAdmin> findCheckuserByName(String key) {
		MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<MedicalAdmin> list = this.iBaseDao.getBySql("from MedicalAdmin a where a.enterpriseId=? and a.group.platform.platformType=? and a.name like ? ", null
				, user.getEnterpriseId()
				,SystemConfig.ORDERS_CENTER_TYPE
				,"%"+key+"%");
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalLogistics> findLogisticsList(MedicalAdmin admin) {
		return this.iBaseDao.getBySql("from MedicalLogistics a where a.hospitalId=? ", null, admin.getEnterpriseId());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalCallTelInfo> findTelInfoList(String cId) {
		return this.iBaseDao.getBySql("from MedicalCallTelInfo a where a.customerId=? ", null, cId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalKeyValue> findSystemList(String typeName) {
		List<MedicalKeyValue> keyValList = this.iBaseDao.getBySql("from MedicalKeyValue a where a.typeName=? ", null, typeName);
		Iterator<MedicalKeyValue> keyValIter = keyValList.iterator();
		while(keyValIter.hasNext()) {
			MedicalKeyValue keyVal = keyValIter.next();
			if(SystemConfig.HM_SYSTEM_TYPE.equals(keyVal.getKeyName()) || 
					SystemConfig.SS_SYSTEM_TYPE.equals(keyVal.getKeyName()) || 
					SystemConfig.MM_SYSTEM_TYPE.equals(keyVal.getKeyName())) {
				keyValIter.remove();
			}
		}
		return keyValList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalKeyValue> findOrderStatusList(String systemType) {
		List<MedicalKeyValue> keyValList = this.iBaseDao.getBySql("from MedicalKeyValue a where a.typeName=? and a.systemType=? ", null, SystemConfig.ORDERS_STATUS, systemType);
		return keyValList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Page findMyOrdersByPage(MedicalOrdersStorage ordersStorage, Map<String, Object> map) {

		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrdersStorage a where 1=1 and a.checkUserId=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalOrdersStorage a where 1=1 and a.checkUserId=? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(ordersStorage.getCheckUserId());
		
		if(StringUtils.isNotBlank(ordersStorage.getSerialNum())) {
			countSql.append(" and a.serialNum = ? ");
			statusSql.append(" and a.serialNum = ? ");
			objectList.add(ordersStorage.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(ordersStorage.getExpressId())) {
			countSql.append(" and a.expressId = ? ");
			statusSql.append(" and a.expressId = ? ");
			objectList.add(ordersStorage.getExpressId());
		}
		
		if(StringUtils.isNotBlank(ordersStorage.getName())) {
			countSql.append(" and a.name = ? ");
			statusSql.append(" and a.name = ? ");
			objectList.add(ordersStorage.getName());
		}
		
		if(null != ordersStorage.getStartTime()) {
			countSql.append(" and a.checkTime >= ? ");
			statusSql.append(" and a.checkTime >= ? ");
			objectList.add(ordersStorage.getStartTime());
		}
		
		if(null != ordersStorage.getStime()) {
			countSql.append(" and a.createTime >= ? ");
			statusSql.append(" and a.createTime >= ? ");
			objectList.add(ordersStorage.getStime());
		}
		
		if(StringUtils.isNotBlank(ordersStorage.getKeyType()) && StringUtils.isNotBlank(ordersStorage.getStatus())) {
			if(ordersStorage.getKeyType().equals(SystemConfig.CM_SYSTEM_TYPE)) {
				countSql.append(" and a.callStatus = ?");
				statusSql.append(" and a.callStatus = ?");
				objectList.add(ordersStorage.getStatus());
			}
			
			if(ordersStorage.getKeyType().equals(SystemConfig.OM_SYSTEM_TYPE)) {
				countSql.append(" and a.ordersStatus = ?");
				statusSql.append(" and a.ordersStatus = ?");
				objectList.add(ordersStorage.getStatus());
			}
			
			if(ordersStorage.getKeyType().equals(SystemConfig.WM_SYSTEM_TYPE)) {
				countSql.append(" and a.warehouseStatus = ?");
				statusSql.append(" and a.warehouseStatus = ?");
				objectList.add(ordersStorage.getStatus());
			}
			
			if(ordersStorage.getKeyType().equals(SystemConfig.FM_SYSTEM_TYPE)) {
				countSql.append(" and a.financialStatus = ?");
				statusSql.append(" and a.financialStatus = ?");
				objectList.add(ordersStorage.getStatus());
			}
		}
		
		// 排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils.isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])) {
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]);
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		
		List<MedicalOrdersStorage> list = new ArrayList<MedicalOrdersStorage>();
		for(Object obj : page.getResult()) {
			MedicalOrdersStorage ordersFindStorage = (MedicalOrdersStorage) obj;
			// 订单详细
			List<MedicalOrdersProduct> ordersProductList = this.iBaseDao.getBySql("from MedicalOrdersProduct a where a.ordersId=? ", null, ordersFindStorage.getId());
			StringBuilder ordersDetail = new StringBuilder("");
			for(MedicalOrdersProduct ordersProduct : ordersProductList) {
				ordersDetail.append(ordersProduct.getMedicine().getName());
				ordersDetail.append("*");
				ordersDetail.append(ordersProduct.getQuantity());
				ordersDetail.append("；");
			}
			if(StringUtils.isNotBlank(ordersDetail.toString())) {
				ordersDetail.deleteCharAt(ordersDetail.lastIndexOf("；"));
			}
			ordersFindStorage.setOrdersProduct(ordersDetail.toString());
			
			if(StringUtils.isNotBlank(ordersFindStorage.getExpressId())) {
				MedicalLogistics logistics = (MedicalLogistics) this.iBaseDao.getObject(MedicalLogistics.class, ordersFindStorage.getExpressId());
				if(null != logistics) {
					ordersFindStorage.setExpressName(logistics.getName());
				}
			}
			list.add(ordersFindStorage);
		}
		page.setResult(list);
		return page;
	}
}
